package com.android.readcard.write;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;

import com.android.readcard.inter.ReadIccidListener;
import com.android.readcard.inter.WriteCardListener;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.Busi_Idcard_device;
import com.android.readcard.utils.TextUtil;
import com.sunnada.bluetooth.SYDBlueReaderHelper;

import java.lang.reflect.Method;

/**
 * 恒鸿达写卡
 */

public class HHDWrite {
    /**
     * 恒鸿达所需
     */
    private AsyncTask<String, Void, Void> mTask = null;
    private static String mResultMsg = null;
    public Busi_Idcard_device midHandler;

    public SYDBlueReaderHelper mIdUtil;
    private String blueAddress;
    private Activity mActivity;
    private ReadIccidListener mReadIccidListener;
    private WriteCardListener mWriteCardListener;
    private int mType;

    public HHDWrite(Activity context, int mType, Busi_Idcard_device midHandler, SYDBlueReaderHelper mIdUtil, String blueAddress, ReadIccidListener readIccidListener
            , WriteCardListener writeCardListener) {
        this.mActivity = context;
        this.mType = mType;
        this.midHandler = midHandler;
        this.mIdUtil = mIdUtil;
        this.blueAddress = blueAddress;
        this.mReadIccidListener = readIccidListener;
        this.mWriteCardListener = writeCardListener;
    }

    //******************************************读iccid************************************************
    public void connect() {
        boundBlueToothDevice();
        ReadHHDIccid();
    }

    // 恒鸿达 读取 ICCID
    private void ReadHHDIccid() {
//        Common.progressbarInit(mActivity, "读取IC卡", "读取ICCID。。。"); // 进度条
        mTask = new AsyncTask<String, Void, Void>() {
            int ret = -1;
            byte[] iccid = new byte[32];
            @SuppressWarnings("unused")
            byte[] iccid_len = new byte[1];
            @SuppressWarnings("unused")
            byte[] sim2g = new byte[48];
            byte[] sim2g_len = new byte[2];
            byte[] sim3g = new byte[48];
            byte[] sim3g_len = new byte[2];
            byte[] check_out = new byte[2];

            @Override
            protected Void doInBackground(String... params) {
                try {
                    if (mIdUtil.registerBlueCard(blueAddress)) {
                        if (mIdUtil.Mini_handshake_mid() != 1) {
//                            mResultMsg = "握手失败";
                            mReadIccidListener.readIccidErr("读取ICCID失败,请重新读卡!");
                            ret = -1;
                            return null;
                        }
                        int res = mIdUtil.readSimICCID(iccid);

                        if (res == -1) {
                            mReadIccidListener.readIccidErr("读取ICCID失败,请重新读卡!");
                            return null;
                        }
                        res = mIdUtil.Mini_sim_blank_check_mid((byte) 1, check_out,
                                sim2g_len, sim2g, sim3g_len, sim3g);

                        if (res != -1) {
                            ret = 1;
                        }
                    }
                    return null;
                } catch (Exception e) {
                    mReadIccidListener.readIccidErr("读取ICCID失败,请重新读卡!");
                    e.printStackTrace();
                }
                return null;
            }

            // 恒鸿达读取卡数据 ICCID
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
//                Common.progressbarEnd();
                if (ret == -1) {
                    mReadIccidListener.readIccidErr("读取ICCID失败,请重新读卡!");
                } else {
                    String imis = TextUtil.bytesToASCString(sim3g);

                    if (mType == 0) {
                        if (!BleGlobUtils.isNum(imis)) {
                            mReadIccidListener.readIccidIsChengKa(1617, new String(iccid).trim(), "此卡是白卡,无需重置");
                        } else {
                            // 读iccid成功
                            mReadIccidListener.readIccidSuc(3, new String(iccid).trim(), imis);
                        }
                    } else {
                        if (BleGlobUtils.isNum(imis)) {
                            mReadIccidListener.readIccidIsChengKa(1617, new String(iccid).trim(), "此卡是成卡,请换卡重试");
                        } else {
                            // 读iccid成功
                            mReadIccidListener.readIccidSuc(3, new String(iccid).trim(), imis);
                        }
                    }
                }
                mTask = null;
            }
        };
        mTask.execute("");


    }

    //***********************************写卡******************************
    // 恒鸿达写卡
    public void writeIccidData(final String imsiid, final String mscid) {
        // 开启异步任务。。
        // 如果读取失败则弹出搜索蓝牙
        mTask = new AsyncTask<String, Void, Void>() {
            int ret = -1;

            @Override
            protected Void doInBackground(String... params) {
                byte[] iccidb = new byte[32];
                byte[] iccidb_len = new byte[1];
                byte[] sim2g = new byte[48];
                byte[] sim2g_len = new byte[2];
                byte[] sim3g = new byte[48];
                byte[] sim3g_len = new byte[2];
                byte[] check_out = new byte[2];
                int res = 1;
                if (mIdUtil.registerBlueCard(blueAddress)) {
                    try {
                        if (mIdUtil.Mini_handshake_mid() != 1) {
                            ret = -1;
                            mResultMsg = "握手失败";
                            return null;
                        }
                        ret = mIdUtil.Mini_sim_iccid_get_mid(iccidb_len, iccidb);
                        if (ret != -1) {
                            // 读取sim卡号。以便判断是否是白卡。
                            boolean isblank = false;
                            res = mIdUtil.Mini_sim_blank_check_mid((byte) 1, check_out,
                                    sim2g_len, sim2g, sim3g_len, sim3g);
                            if (res != -1) {
                                if (check_out[0] == 0x00)
                                    isblank = true;
                            }
                            // 如果不是白卡则告诉这个卡上有数据不能写入
                            if (!isblank) {
                                ret = -1;
                                mResultMsg = "此卡为成卡，无需写入";
                                return null;
                            }
                            ret = mIdUtil.Mini_sim_imsi_write_mid(imsiid.getBytes(),
                                    imsiid.getBytes());
                            if (ret > 0) {
                                // 短信中心写入可以失败！！
                                ret = mIdUtil.Mini_sim_smsc_write_mid(mscid.getBytes());
                                return null;
                            }
                            mResultMsg = "写IMSI失败";
                        }
                    } catch (Exception e) {
                        ret = -1;
                        e.printStackTrace();
                    }
                }
                return null;
            }

            // 恒鸿达 写卡数据 写IMSI
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
//                Common.progressbarEnd();
                if (ret == -1) {
                    // 写卡失败
                    mWriteCardListener.writeErr();
                } else {
                    // 写卡成功
                    mWriteCardListener.writeSuc();
                }
                mTask = null;
            }
        };
        mTask.execute("");
    }

    /**
     * 绑定蓝牙
     */
    private void boundBlueToothDevice() {
        try {
            BluetoothDevice device = BluetoothAdapter
                    .getDefaultAdapter().getRemoteDevice(blueAddress);
            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                Method createBondMethod = device.getClass().getMethod(
                        "createBond");
                createBondMethod.invoke(device);
            }
        } catch (Exception e) {
            mReadIccidListener.readIccidErr("设备连接失败,请重新配对");
            e.printStackTrace();
        }
    }
}
